package com.cedric.component;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.cedric.entity.DelayJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: delay-queue
 * @description: 延迟任务，使用可排序的ZSet保存数据，提供取出最小值等操作
 * @author: 史偕成
 * @create: 2021/09/26 21:01
 **/
@Slf4j
@Component
public class DelayBucket {

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 原子类型
     */
    private static final AtomicInteger INDEX = new AtomicInteger(0);

    @Value("${thread.size}")
    private int bucketsSize;

    private List<String> bucketNames = new ArrayList<>();

    /**
     * @return
     */
    @Bean
    public List<String> createBuckets() {
        for (int i = 0; i < bucketsSize; i++) {
            bucketNames.add("bucket" + i);
        }
        return bucketNames;
    }

    /**
     * 获取当前桶名称
     *
     * @return
     */
    private String getThisBucketName() {
        int tIndex = INDEX.addAndGet(1);
        int i1 = tIndex % bucketsSize;
        return bucketNames.get(i1);
    }

    /**
     * 获取桶集合
     * @param bucketName
     * @return
     */
    private BoundZSetOperations getBucket(String bucketName) {
        return  redisTemplate.boundZSetOps(bucketName);
    }


    /**
     * 放入延迟任务
     * @param delayJob
     */
    public void addDelayJob(DelayJob delayJob) {
        log.info("[添加延迟任务]: {}", JSON.toJSONString(delayJob));
        String thisBucketName = getThisBucketName();
        BoundZSetOperations bucket = getBucket(thisBucketName);
        bucket.add(delayJob, delayJob.getDelayDate());
    }

    /**
     * 获取最新的延迟任务
     * @param index
     * @return
     */
    public DelayJob getFirstDelayTime(Integer index) {
        String name = bucketNames.get(index);

        BoundZSetOperations bucket = getBucket(name);

        Set<ZSetOperations.TypedTuple> set = bucket.rangeWithScores(0, 1);

        if (CollectionUtil.isEmpty(set)) {
            return null;
        }
        ZSetOperations.TypedTuple typedTuple = (ZSetOperations.TypedTuple<String>) set.toArray()[0];
        Object value = typedTuple.getValue();

        if (value instanceof DelayJob) {
            return (DelayJob) value;
        }
        return null;
    }

    /**
     * 移除延迟任务
     * @param index
     * @param job
     */
    public void removeDelayTime(Integer index, DelayJob job) {
        String bucketName = bucketNames.get(index);

        BoundZSetOperations bucket = getBucket(bucketName);

        bucket.remove(job);
    }
}
